import React, { useState, useEffect } from 'react';
import { Input, Popover } from 'antd';
import IconPro from '@/components/IconPro';
import { formatMessage } from 'umi';

/**
 * @description 右侧有校验气泡框的密码输入组件
 * @param {Array} validatorList 要校验的规则字符串数组，默认"长度为8-20个字符"，"需同时包含大小写字母及数字"两条规则
 * @param {Function | Array} checkList 可执行函数，最终返回一个校验通过的规则数组；或者直接返回校验通过的规则数组
 */
const PopoverPasswordInput = React.forwardRef(({ validatorList, checkList, ...rest }, ref) => {
    const [popContent, setPopContent] = useState([]);
    const [checkArray, setcheckArray] = useState([]);
    const [isVisible, setIsVisible] = useState(false);
    const { errors } = rest['data-__field'] || {};

    useEffect(() => {
        if (typeof checkList === 'function') {
            const result = checkList();
            setcheckArray(Array.isArray(result) ? result : []);
        } else {
            setcheckArray(checkList || []);
        }
    }, [checkList]);

    // 气泡框内容
    useEffect(() => {
        const defalutArr = [
            formatMessage({
                id: 'form.passwordRuleStep1.validate'
            }),
            formatMessage({
                id: 'form.passwordRuleStep2.validate'
            })
        ];
        if (validatorList && Array.isArray(validatorList)) {
            setPopContent(validatorList);
        } else {
            setPopContent(defalutArr);
        }
    }, [validatorList]);

    // 有错误出现气泡框
    useEffect(() => {
        if (errors) {
            setIsVisible(true);
        }
    }, [errors]);

    return (
        <Popover
            ref={ref}
            content={
                <div>
                    {popContent.map(item => {
                        const isPass = checkArray.includes(item);
                        return (
                            <div key={item} style={{ color: isPass ? '#44C69D' : '#F55555' }}>
                                <IconPro type={isPass ? 'check-circle' : 'close-circle'} style={{ marginRight: 6 }} />
                                {item}
                            </div>
                        );
                    })}
                </div>
            }
            placement="right"
            visible={isVisible}
        >
            <Input.Password
                onFocus={() => {
                    if (errors) {
                        setIsVisible(true);
                    }
                }}
                onBlur={() => {
                    if (!errors) {
                        setIsVisible(false);
                    }
                }}
                placeholder="请输入"
                allowClear
                autoComplete="off"
                {...rest}
            />
        </Popover>
    );
});
export default PopoverPasswordInput;
